package cn.yeziji.forum.dao.iquery;

import cn.org.atool.fluent.mybatis.If;
import cn.org.atool.fluent.mybatis.base.crud.IQuery;
import cn.org.atool.fluent.mybatis.base.crud.JoinBuilder;
import cn.yeziji.forum.entity.ForumAnswerEntity;
import cn.yeziji.forum.entity.ForumUserEntity;
import cn.yeziji.forum.entity.ForumUserQaEntity;
import cn.yeziji.forum.wrapper.*;

/**
 * 回复查询构造器
 *
 * @author gzkemays
 * @since 2022/11/14 4:04 PM
 */
public class AnswerQuery {
  public static IQuery<ForumAnswerEntity> getUser7DaysAnswerQuery(Integer userId) {
    return new ForumAnswerQuery("fa")
        .selectAll()
        .where
        .userId()
        .eq(userId)
        .and(
            q ->
                q.where
                    .applyFunc(
                        "DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(fa.createTime) or DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(fa.updateTime)")
                    .end())
        .end();
  }

  public static IQuery getAnswerByQuestionIdQuery(Integer questionId, Integer userId) {
    return JoinBuilder.from(
            new ForumAnswerQuery("fa")
                .select
                .id()
                .content()
                .parentAnswerId()
                .goodNumber()
                .createTime()
                .updateTime()
                .end()
                .groupBy
                .id()
                .end()
                .orderBy
                .goodNumber()
                .desc()
                .createTime()
                .asc()
                .updateTime()
                .asc()
                .end())
        .leftJoin(
            new ForumQuestionAnswerQuery("fqa")
                .select
                .questionId()
                .end()
                .where
                .questionId()
                .eq(questionId)
                .end())
        .onApply("fqa.answerId in (fa.id, fa.parentAnswerId)")
        .endJoin()
        .leftJoin(new ForumUserQuery("fu").select.nickname().avatar().desc().end())
        .onEq(ForumAnswerEntity::getUserId, ForumUserEntity::getId)
        .endJoin()
        .leftJoin(new ForumUserQaQuery("fuqa").select.toOpera().end())
        .onEq(ForumAnswerEntity::getId, ForumUserQaEntity::getAnswerId)
        .onRight(query -> query.where.userId().eq(userId, If::notNull))
        .endJoin()
        .build();
  }
}
